package com.lantu.wisdom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lantu.framework.common.constants.exceptions.ASException;
import com.lantu.framework.common.utils.BeanMapper;
import com.lantu.paycommon.utils.StringUtil;
import com.lantu.wisdom.common.enums.code.ParamResponseCode;
import com.lantu.wisdom.common.utils.CreateCodeUtil;
import com.lantu.wisdom.dto.AddUserDTO;
import com.lantu.wisdom.mapper.WUserMapper;
import com.lantu.wisdom.model.WUser;
import com.lantu.wisdom.service.WUserApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zch
 * @since 2021-06-15
 */
@Service
@Slf4j
public class WUserServiceImpl extends ServiceImpl<WUserMapper, WUser> implements WUserApi {


    /**
     * 新注册用户
     *
     * @param addUserDTO
     * @return
     */
    @Override
    public boolean addUser(AddUserDTO addUserDTO) {
        WUser userInfo = this.getOne(new LambdaQueryWrapper<WUser>().eq(WUser::getOpenId, addUserDTO.getOpenId()));
        if (null != userInfo) {
            throw new ASException(ParamResponseCode.OPENID_EXIST_ERRO);
        }
        userInfo = BeanMapper.map(addUserDTO, WUser.class);
        userInfo.setUserId(CreateCodeUtil.createUserCode());
        userInfo.setCreateTime(System.currentTimeMillis());
        //如果老用户邀请人数达到5人次数加1
        if (StringUtil.isNotNull(addUserDTO.getFromBy())) {
            int count = count(new LambdaQueryWrapper<WUser>().eq(WUser::getFromBy, addUserDTO.getFromBy()));
            count++;
            if (count % 5 == 0) {
                WUser user = getOne(new LambdaQueryWrapper<WUser>().eq(WUser::getUserId, addUserDTO.getFromBy()));
                if (null != user) {
                    user.setNum(user.getNum() + 1);
                    updateById(user);
                }
            }
        }
        return this.save(userInfo);
    }

    /**
     * 根据openId获取用户详情
     *
     * @param openId
     * @return
     */
    @Override
    public WUser getUserInfoByOpenId(String openId) {
        WUser userInfo = this.getOne(new LambdaQueryWrapper<WUser>().eq(WUser::getOpenId, openId));
        return userInfo;
    }

    /**
     * 获取用户咨询次数
     *
     * @param userId
     * @return
     */
    @Override
    public Integer getUserNum(String userId) {
        WUser wUser = getOne(new LambdaQueryWrapper<WUser>().eq(WUser::getUserId, userId));
        return wUser.getNum();
    }
}
